
import request from "./request.js"

export const PUBLIC = {
	/**
	 * timestamp 时间戳
	 * formatStr 结果的字符串模板 yyyy.MM.dd hh:mm:ss  yyyy.MM.dd 等等 默认为yyyy.MM.dd hh:mm:ss
	 */
	formatTime: (timestamp, formatStr) => {
		if (!timestamp) return '-'
		let d = new Date()
		d.setTime(timestamp)
		let obj = {
			'M+': d.getMonth() + 1,
			'd+': d.getDate(),
			'h+': d.getHours(),
			'm+': d.getMinutes(),
			's+': d.getSeconds(),
			'q+': Math.floor((d.getMonth() + 3) / 3),
			'S+': d.getMilliseconds()
		}
		formatStr = formatStr || 'yyyy-MM-dd hh:mm:ss'
		if (/(y+)/i.test(formatStr)) {
			formatStr = formatStr.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
		}
		for (var k in obj) {
			if (new RegExp('(' + k + ')').test(formatStr)) {
				formatStr = formatStr.replace(RegExp.$1, RegExp.$1.length === 1
					? obj[k] : ('00' + obj[k]).substr(('' + obj[k]).length))
			}
		}
		return formatStr
	},
	// 清除本地缓存
	clearStorage: () => {
		uni.removeStorageSync('token')
	},
	// 去除空格
	trim(str) {
		return str.replace(/\s*/g, "")
	},
	/**
	 * 确定值是否为对象
	 *
	 * @param {Object} obj 传入的对象
	 * @returns {String} 返回类型
	 */
	getObjClass(obj) {
		return Object.prototype.toString.call(obj).slice(8, -1)
	},
	/**
	 * 深度克隆
	 *
	 * @param {Object} obj 传入需要克隆的对象
	 * @returns {Object} 返回克隆好的对象
	 */
	deepClone(obj) {
		let result
		let objClass = PUBLIC.getObjClass(obj)
		if (objClass === 'Object') {
			result = {}
		} else if (objClass === 'Array') {
			result = []
		} else {
			return obj // 如果是其他数据类型不复制，直接将数据返回
		}
		// 遍历目标对象
		for (let key in obj) {
			let value = obj[key]
			result[key] = PUBLIC.deepClone(value)
		}
		return result
	},
	/**
	 * 返回一个只有列入挑选key属性的对象
	 * @param {*} obj 来源对象
	 * @param {*} arr 需要挑选的属性数组
	 * @returns 返回object中选中的属性的对象
	 */
	pick(obj, arr) {
		// newObj=>上一次调用 callbackFn 时的返回值, item=>数组中正在处理的元素, {} => 初始值
		let pickObj = arr.reduce((newObj, item) => {
			if (item in obj) {
				newObj[item] = obj[item]
			}
			return newObj
		}, {})
		return PUBLIC.deepClone(pickObj)
	},
	/**
	 * 返回一个没有列入排除key属性的对象
	 * @param {*} obj 来源对象
	 * @param {*} arr 需要排除的key属性数组
	 */
	omit(obj, arr) {
		const newObj = {};
		const keys = Object.keys(obj)
		for (const key of keys) {
			if (arr.indexOf(key) === -1) {
				newObj[key] = obj[key]
			}
		}
		return PUBLIC.deepClone(newObj)
	},
	// 随机生成位数，默认八位数
	getRandom: (len) => {
		let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
		let uuid = []
		let i
		len = len || 8
		for (i = 0; i < len; i++) {
			uuid[i] = chars[0 | Math.random() * chars.length]
		}
		return uuid.join('')
	},
	// 根据字典值匹配对应的值名称
	findDicText(array, value, config) {
		const { dictCode = 'dictCode', dictValue = 'dictValue' } = config || {}
		let item = array.find(val => val[dictCode] == value)
		if (item) {
			return item[dictValue]
		} else {
			return ''
		}
	},
	getDict(value, config) {
    return new Promise((resolve, reject) => {
      if(value == 'BIZ_FMT_BANK') {
        request({
          url: URL_link.findByDictList,
          method: "post",
          hideLoading: true,
          data: {
            dictCode: "COM001",
            dictTypeCode: "csp_common"
          }
        }).then(res => {
          let filterArr = res.data.code == 200 && res.data.data?.length ? res.data.data[0].dictValue.split(',') : ''
          this.handleDic(value,config,resolve, reject,filterArr)
        }).catch(err=>{
          this.handleDic(value,config,resolve, reject)
        })
      }else this.handleDic(value,config,resolve, reject)
    });
  },

  handleDic(value,config,resolve, reject,filterArr){
    const { valueKey = 'dictCode', textKey = 'dictValue',keyword = '' } = config || {}
		let params = {dictName: value}
		if (keyword)  params.keyword = keyword
    request({
      url: URL_link.queryDictType,
      method: "GET",
      hideLoading: true,
      data: params
    }).then(res => {
      let DictList = [];
      let data = res.data?.data;
      if (data && typeof data === "object" && data.length) {
        if(filterArr) data = data.filter(fItem => !filterArr.some(sItem=> sItem === fItem.code))
        data.map(item => {
          if (item.hasOwnProperty("code") && item.hasOwnProperty("text")) {
            DictList.push({ [textKey]: item.text, [valueKey]: item.code });
          }
        });
      }
      resolve(DictList);
    });
  },
	getAttr(array, dict, that) {
		array.forEach(v => {
			if (dict[v] && !that[v].length) {
				// console.log('字典表', v)
				that.$set(that, v, dict[v])
			}
		})
	},
	substrDate(string) {
		if (string && typeof (string) === 'string') {
			return string.substring(0, 10)
		} else {
			return string
		}
	},
	login(token) {
		Hola.setStorageSync('token', token)
		this.getUserInfo(token)
	},
	logout() {
		if (window.projectStore) {
			window.projectStore.commit('logout');
		}
		Hola.removeStorageSync('token')
		if (window.projectGlobaldata) {
			window.projectGlobaldata.userInfo = Object.assign({})
		}
	},
	getUserInfo(token) {
		// if (!token) return
		request({
			url: window?.LOCAL_CONFIG?.user_service_api ? `${window.LOCAL_CONFIG.user_service_api}/user/bind/login/info` : '/user/bind/login/info',
			method: "GET",
			header: {
				'X-Nf-Access-Token':token || ''
			},
		}).then(res => {
			const data = res.data?.data
			if (window.projectStore) {
				window.projectStore.commit('changeStatus', data.loginStatus === '1')
				window.projectStore.commit('userInfo', data || {})
			}
			if (data.realAuthStatus === '1') {
				if (window.projectGlobaldata) {
					window.projectGlobaldata.userInfo = Object.assign({}, {
						birthDate: data.birthday,
						accidentName: data.certiName,
						certiType: data.certiType,
						certiCode: data.certiCode,
						gender: data.gender,
						mobile: data.mobile
					})
				}
			} else {
				if (window.projectGlobaldata) {
					window.projectGlobaldata.userInfo = Object.assign({})
				}
			}
		})
	},
	generatekey(num) {
		let library =
			"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		let key = "";
		for (let i = 0; i < num; i++) {
			let randomPoz = Math.floor(Math.random() * library.length);
			key += library.substring(randomPoz, randomPoz + 1);
		}
		return key;
	},
	getSecretId() {
		return new Promise((resolve, reject) => {
			const plaintext = this.generatekey(32)
			Hola.request({
				url: window?.LOCAL_CONFIG?.gateway_service_api ? `${window.LOCAL_CONFIG.gateway_service_api}/security/secret/consult` : '/security/secret/consult',
				method: "POST",
				timeout: 180000,
				data: {},
				//  dataType: "json",
				success: res => {
					if (res.statusCode === 200) {
						const pubKey = res.data?.data.secretId
						Hola.setStorageSync('sm4', plaintext)
						Hola.setStorageSync('secretId', pubKey)
						resolve(pubKey);
					}
				},
				fail: async err => {
					Hola.showToast({
						title: err.msg,
						icon: "none",
						duration: 3000
					});
					reject(err);
				},
				complete: res => {
				}
			});
		})
	},
	weixinUrl(count) {
		// let appid = window?.LOCAL_CONFIG?.wechat_app_id || ''; //微信APPid
		let local = window.location.href.split('?')[0].split('#')[0] + window.location.hash;
		// console.log("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
		// 	appid +
		// 	"&redirect_uri=" +
		// 	encodeURIComponent(local) +
		// 	"&response_type=code&scope=snsapi_userinfo&state=" + (count || 'STSTE') + "#wechat_redirect"
		// )
		// //不存在就打开上面的地址进行授权
		// window.location.href =
		// 	"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
		// 	appid +
		// 	"&redirect_uri=" +
		// 	encodeURIComponent(local) +
		// 	"&response_type=code&scope=snsapi_userinfo&state=" + (count || 'STSTE') + "#wechat_redirect"
		request({
			url: window?.LOCAL_CONFIG?.user_service_api ? `${window.LOCAL_CONFIG.user_service_api}/user/auth/wechat/authUrl` : '/user/auth/wechat/authUrl',
			method: 'Get',
			data: { redirectUri: local, state: count },
			getToken:true
		}).then(res => {
			if (res.data.data) {
				window.location.href = res.data.data
				console.log('authUrl', res.data.data)
			}
		}).catch(err => {
		})
	},
	// 微信，企业微信，支付宝，以后都用这个
	authUrl(count) {
		let local = window.location.href.split('?')[0].split('#')[0] + window.location.hash;
		let authUrl = judegeIsAlipay() ? '/user/auth/alipay/authUrl' : '/user/auth/wechat/authUrl';
		request({
			url: window?.LOCAL_CONFIG?.user_service_api ? `${window.LOCAL_CONFIG.user_service_api}${authUrl}` : authUrl,
			method: 'Get',
			data: { redirectUri: local, state: count },
			getToken:true
		}).then(res => {
			if (res.data.data) {
				console.log('authUrl', res.data.data)
				window.location.href = res.data.data
			}
		}).catch(err => {
		})
	},
	getUrlCode() {
		// 截取url中的code方法 微信登陆用
		var url = location.search;
		var theRequest = new Object();
		if (url.indexOf("?") != -1) {
			var str = url.substr(1);
			var strs = str.split("&");
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
			}
		}
		console.log(theRequest);
		return theRequest;
	},
	// 获取url中的某个参数
	getParamFromURL(url, paramName) {
		const urlParams = url.split('?')[1]; // 获取URL中'?'后面的部分
		if (!urlParams) return null; // 如果没有查询参数，则返回null
	
		const paramsArray = urlParams.split('&'); // 将参数字符串按'&'分割成数组
		for (let i = 0; i < paramsArray.length; i++) {
			const param = paramsArray[i].split('='); // 再将每个键值对按'='分割
			if (decodeURIComponent(param[0]) === paramName) { // 检查是否为所需参数名
				return decodeURIComponent(param[1]); // 返回对应的参数值（已解码）
			}
		}
		return null; // 如果未找到参数，则返回null
	},
	//blob 转 64
	blobToBase64(blob, callback) {
		const fileReader = new FileReader();
		fileReader.onload = (e) => {
			callback(e.target.result);
		};
		fileReader.readAsDataURL(blob);
	},
	isWx() {
		return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger"
	},
	//是否企业微信
  isWework() {
    return (
      String(navigator.userAgent.toLowerCase().match(/wxwork/i)) ===
      'wxwork'
    )
  },
}
// 是否是pad端
export const isPad = () => {
	// pad域名判断
	// let padHost = [
	// 	'fbcp-pad-uat.kdlins.com.cn',
	// 	'fbcp-pad.kdlins.com.cn'
	// ]
	
	// return padHost.includes(window.location.hostname) 
	return window.location.hostname.includes('fbcp-pad')
}
// 是否采用pad版样式
export const isPadStyle = () => {
	let padStyleByMinWidth = 1024
	let width = document.documentElement.clientWidth
	return width >= padStyleByMinWidth && isPad()
}
// 判断是否为支付宝环境
export const judegeIsAlipay = () => {
	return navigator && navigator.userAgent.indexOf('AliApp') > -1
}
export const alipayReady = (callback) => {
  // 如果jsbridge已经注入则直接调用
  if (window.AlipayJSBridge) {
    callback && callback();
  } else {
    // 如果没有注入则监听注入的事件
    document.addEventListener('AlipayJSBridgeReady', callback, false);
  }
}
export function hideload(){
	uni.hideLoading()
}
// 节流
export function throttle(func, delay,timer) {
	if (!timer) {
		timer = setTimeout(() => {
			func();
			timer = null;
		}, delay);
	}
}
export function isWxMiniProgram() {
	return (
		String(navigator.userAgent.toLowerCase().match(/miniprogram/i)) === "miniprogram"
	)
}